package com.gelpag.base.business.login;

import been.RoleInfo;
import been.UserInfo;
import com.gelpag.base.business.user.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tools.utils.Common;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    UserMapper userMapper;

    @Resource
    LoginMapper loginMapper;

    public boolean checkUserInfo(UserInfo userInfo) {

        String login_password = userInfo.getLogin_password();

        userInfo.setMd5_login_password(Common.MD5Encrypt(login_password));
        int cnt = loginMapper.checkUserInfo(userInfo);

        return cnt == 1 ? true : false;
    }



//    public boolean checkUserInfo(Map<String, String> loginMap) {
//
//        String login_password = loginMap.get("login_password");
//        logger.debug(Common.MD5Encrypt(login_password));
//        loginMap.put("md5_login_password", Common.MD5Encrypt(login_password));
//        int cnt = loginMapper.checkUserInfo(loginMap);
//        logger.debug(cnt+"");
//
//        return cnt == 1 ? true : false;
//    }

    public String createToken(String login_name) {

        UserInfo userInfo = userMapper.getUserInfo(login_name);
        //用户拥有角色
        List<RoleInfo> userRoles = userMapper.getUserRoles(userInfo);
        //用户所属部门
        List<String> unit_ids = userMapper.getUnitIdsByUserId(userInfo.getUser_id());

        List<String> role_ids = new ArrayList<>();
        for (RoleInfo role : userRoles) {
            role_ids.add(role.getRole_id());
        }

        //根据用户信息，用户角色，用户所属部门 生成token
        HashMap<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("user_id", userInfo.getUser_id());
        userMap.put("user_name", userInfo.getUser_name());
        userMap.put("user_type", userInfo.getUser_type());
        userMap.put("roles", role_ids);
        userMap.put("unit_ids", unit_ids);
        userMap.put("unit_id", unit_ids != null && unit_ids.size() > 0 ? unit_ids.get(0) : null);

        return Common.generateToken(userMap);
    }
}
